package com.hmall.api.config;

import com.hmall.common.utils.UserContext;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-11-06 20:20
 **/
@Configuration
public class RabbitTemplateConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setBeforePublishPostProcessors(message -> {
            System.out.println("消息发送前处理" + UserContext.getUser());
            // 自动将当前用户信息添加到消息头
            message.getMessageProperties().setHeader("user-info", UserContext.getUser());
            return message;
        });
        return template;
    }
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer,
            ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        factory.setAfterReceivePostProcessors(message -> {
            // 从消息头提取用户信息并设置到上下文
            Object userInfo = message.getMessageProperties().getHeaders().get("user-info");
            if (userInfo != null) {
                UserContext.setUser((Long) userInfo);
            }
            return message;
        });
        return factory;
    }
}
